import base64
import io

import requests
from PIL import Image


def find_substring_positions(text, substring):
    positions = []
    pos = text.find(substring)

    while pos != -1:
        positions.append(pos)
        pos = text.find(substring, pos + 1)

    return positions


def extract_images_from_xls(file_path, output_dir, out_file_name):
    # 读取整个文件数据
    with open(file_path, 'rb') as f:
        data = f.read()

    # 定义JPEG和PNG文件的开始和结束标记
    markers = {
        'png': {
            'start': b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A',
            'end': b'\x49\x45\x4E\x44\xAE\x42\x60\x82'
        },
        'jpg': {
            'start': b'\xFF\xD8',
            'end': b'\xFF\xD9'
        }
    }
    image_count = 0
    for fmt, marker in markers.items():
        start_list = find_substring_positions(data, marker['start'])
        end_list = find_substring_positions(data, marker['end'])
        for start in start_list:
            for end in end_list:
                if end <= start:
                    continue
                end_ = end + len(marker['end'])
                img_data = data[start:end_]
                try:
                    img = Image.open(io.BytesIO(img_data))
                    img_path = f"{output_dir}/{out_file_name}.png"
                    print(img_path)
                    img = img.resize((60, 84))
                    img.save(img_path, format="PNG")

                    # resize_image(img_path, img_path, 60, 90)
                    image_count += 1
                    print(f"{fmt.upper()} Image saved at: {img_path}")
                    return img_path
                except IOError:
                    print(f"Error opening {fmt.upper()} image at position {start}")


def is_image_openable(image_path):
    try:
        # 尝试打开并加载图片
        img = Image.open(image_path)
        img.load()
        print("Image can be opened and is valid.")
        return True
    except Exception as e:
        print(f"Image cannot be opened: {e}")
        return False


def resize_image(input_path, output_path, target_width, target_height):
    try:
        # 打开图像文件
        image = Image.open(input_path)

        # 调整图像大小
        resized_image = image.resize((target_width, target_height))

        # 保存调整大小后的图像
        resized_image.save(output_path)
        print("图片大小调整成功，已保存到：", output_path)
    except Exception as e:
        print("出现错误：", e)





def download_image(url, save_path):
    """
    下载指定URL的图片并保存到本地。

    :param url: 图片的URL
    :param save_path: 图片保存路径
    """
    try:
        # 发送GET请求
        response = requests.get(url)
        # 检查请求是否成功
        if response.status_code == 200:
            # 打开一个文件以二进制写模式
            with open(save_path, "wb") as file:
                # 将响应内容写入文件
                file.write(response.content)
            print(f"图片下载成功并保存在 {save_path} 文件中")
        else:
            print(f"图片下载失败，状态码：{response.status_code}")
    except Exception as e:
        print(f"发生错误：{e}")


def save_base64_image(base64_image_data, output_path):
    if base64_image_data == "images/code.png":
        download_image("https://inv-veri.chinatax.gov.cn/images/code.png", output_path)
        return
    print(base64_image_data)
    # 从 base64 数据中移除前缀
    base64_image_data = base64_image_data.split(',')[1]

    # 解码 base64 数据
    image_data = base64.b64decode(base64_image_data)

    # 将图片数据写入文件
    with open(output_path, 'wb') as image_file:
        image_file.write(image_data)